package com.xtianzhuang.www.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xtianzhuang.www.dao.TdPermissionMapper;
import com.xtianzhuang.www.dao.TdRoleMapper;
import com.xtianzhuang.www.dao.TdStoryMapper;
import com.xtianzhuang.www.dao.TdTargetMapper;
import com.xtianzhuang.www.dao.TfBudgetMapper;
import com.xtianzhuang.www.dao.TfLoginLogMapper;
import com.xtianzhuang.www.dao.TfUDetailMapper;
import com.xtianzhuang.www.dao.TfUUserMapper;
import com.xtianzhuang.www.dao.TfUserDailyRecordMapper;
import com.xtianzhuang.www.dao.TfUserDailySummaryMapper;
import com.xtianzhuang.www.dao.TfWorkRecordMapper;
import com.xtianzhuang.www.dao.TmRRolePermissionMapper;
import com.xtianzhuang.www.dao.TmSStoryBudgetMapper;
import com.xtianzhuang.www.dao.TmUUserRoleMapper;
import com.xtianzhuang.www.dao.TmUUserStoryMapper;
import com.xtianzhuang.www.dao.TmUUserTargetMapper;
import com.xtianzhuang.www.dao.VRolePermissionMapper;
import com.xtianzhuang.www.dao.VUserBudgetMapper;
import com.xtianzhuang.www.dao.VUserDailySummaryMapper;
import com.xtianzhuang.www.dao.VUserMapper;
import com.xtianzhuang.www.dao.VUserRoleMapper;
import com.xtianzhuang.www.dao.VUserStoryMapper;
import com.xtianzhuang.www.dao.VUserTargetMapper;
import com.xtianzhuang.www.entity.TdPermission;
import com.xtianzhuang.www.entity.TdPermissionExample;
import com.xtianzhuang.www.entity.TdRole;
import com.xtianzhuang.www.entity.TdRoleExample;
import com.xtianzhuang.www.entity.TdStory;
import com.xtianzhuang.www.entity.TdTarget;
import com.xtianzhuang.www.entity.TfBudget;
import com.xtianzhuang.www.entity.TfLoginLog;
import com.xtianzhuang.www.entity.TfLoginLogExample;
import com.xtianzhuang.www.entity.TfUDetail;
import com.xtianzhuang.www.entity.TfUUser;
import com.xtianzhuang.www.entity.TfUUserExample;
import com.xtianzhuang.www.entity.TfUserDailyRecord;
import com.xtianzhuang.www.entity.TfUserDailyRecordExample;
import com.xtianzhuang.www.entity.TfUserDailySummary;
import com.xtianzhuang.www.entity.TfWorkRecord;
import com.xtianzhuang.www.entity.TfWorkRecordExample;
import com.xtianzhuang.www.entity.TmRRolePermission;
import com.xtianzhuang.www.entity.TmRRolePermissionExample;
import com.xtianzhuang.www.entity.TmSStoryBudget;
import com.xtianzhuang.www.entity.TmSStoryBudgetExample;
import com.xtianzhuang.www.entity.TmUUserRole;
import com.xtianzhuang.www.entity.TmUUserRoleExample;
import com.xtianzhuang.www.entity.TmUUserStory;
import com.xtianzhuang.www.entity.TmUUserTarget;
import com.xtianzhuang.www.entity.TmUUserTargetExample;
import com.xtianzhuang.www.entity.VRolePermission;
import com.xtianzhuang.www.entity.VRolePermissionExample;
import com.xtianzhuang.www.entity.VUser;
import com.xtianzhuang.www.entity.VUserBudget;
import com.xtianzhuang.www.entity.VUserBudgetExample;
import com.xtianzhuang.www.entity.VUserDailySummary;
import com.xtianzhuang.www.entity.VUserDailySummaryExample;
import com.xtianzhuang.www.entity.VUserExample;
import com.xtianzhuang.www.entity.VUserRole;
import com.xtianzhuang.www.entity.VUserRoleExample;
import com.xtianzhuang.www.entity.VUserStory;
import com.xtianzhuang.www.entity.VUserStoryExample;
import com.xtianzhuang.www.entity.VUserTarget;
import com.xtianzhuang.www.entity.VUserTargetExample;
import com.xtianzhuang.www.entity.constants.CodeConstants;
import com.xtianzhuang.www.entity.constants.IsDeletedConstants;
import com.xtianzhuang.www.entity.constants.UserTypeConstants;
import com.xtianzhuang.www.entity.others.Lunar;
import com.xtianzhuang.www.entity.others.Solar;
import com.xtianzhuang.www.entity.request.DeleteStoryBudgetRequest;
import com.xtianzhuang.www.entity.request.DeleteSummaryRequest;
import com.xtianzhuang.www.entity.request.DeleteTargetRequest;
import com.xtianzhuang.www.entity.request.LoginRequest;
import com.xtianzhuang.www.entity.request.QueryDailyLifeRequest;
import com.xtianzhuang.www.entity.request.QueryDailyWorkRequest;
import com.xtianzhuang.www.entity.request.SaveBudgetRequest;
import com.xtianzhuang.www.entity.request.SaveRoleRequest;
import com.xtianzhuang.www.entity.request.SaveStoryRequest;
import com.xtianzhuang.www.entity.request.SaveSummaryRequest;
import com.xtianzhuang.www.entity.request.SaveTargetRequest;
import com.xtianzhuang.www.entity.request.SaveUserRequest;
import com.xtianzhuang.www.entity.request.SaveWorkRequest;
import com.xtianzhuang.www.entity.request.UpdatePasswordRequest;
import com.xtianzhuang.www.entity.request.UpdateRolePermissionRequest;
import com.xtianzhuang.www.entity.request.UpdateTargetRequest;
import com.xtianzhuang.www.entity.request.UpdateUserRequest;
import com.xtianzhuang.www.entity.request.UpdateUserRoleRequest;
import com.xtianzhuang.www.entity.response.UpdateTargetResponse;
import com.xtianzhuang.www.service.UserService;
import com.xtianzhuang.www.service.base.BaseServiceBiz;
import com.xtianzhuang.www.utils.LunarSolarConverter;
import com.xtianzhuang.www.utils.LunarUtil;


@Service("userServiceBiz")
@Transactional(rollbackFor = Exception.class)
public class UserServiceBiz extends BaseServiceBiz implements UserService {
	@Autowired
	private TfUUserMapper tfUUserMapper;
	@Autowired
	private TfLoginLogMapper tfLoginLogMapper;
	@Autowired
	private VUserRoleMapper vUserRoleMapper;
	@Autowired
	private TfWorkRecordMapper tfWorkRecordMapper;
	@Autowired
	private TfUserDailyRecordMapper tfUserDailyRecordMapper;
	@Autowired
	private TfUDetailMapper tfUDetailMapper;
	@Autowired
	private TdTargetMapper tdTargetMapper;
	@Autowired
	private TdStoryMapper tdStoryMapper;
	@Autowired
	private TmUUserStoryMapper tmUUserStoryMapper;
	@Autowired
	private TmUUserTargetMapper tmUUserTargetMapper;
	@Autowired
	private VUserStoryMapper vUserStoryMapper;
	@Autowired
	private VUserTargetMapper vUserTargetMapper;
	@Autowired
	private TfUserDailySummaryMapper tfUserDailySummaryMapper;
	@Autowired
	private VUserDailySummaryMapper vUserDailySummaryMapper;
	@Autowired
	private VUserMapper VUserMapper;
	@Autowired
	private TdRoleMapper tdRoleMapper;
	@Autowired
	private TdPermissionMapper tdPermissionMapper;
	@Autowired
	private TmRRolePermissionMapper tmRRolePermissionMapper;
	@Autowired
	private TmUUserRoleMapper tmUUserRoleMapper;
	@Autowired
	private VRolePermissionMapper vRolePermissionMapper;
	@Autowired
	private VUserBudgetMapper vUserBudgetMapper;
	@Autowired
	private TmSStoryBudgetMapper tmSStoryBudgetMapper;
	@Autowired
	private TfBudgetMapper tfBudgetMapper;

	@Override
	public List<TfUUser> selectByExample(TfUUserExample example) {
		// TODO Auto-generated method stub
		return tfUUserMapper.selectByExample(example);
	}

	@Override
	public int insert(TfUUser record) {
		// TODO Auto-generated method stub
		return tfUUserMapper.insert(record);
	}

	@Override
	public void doUserLogin(HttpServletRequest request, LoginRequest loginRequest) throws Exception {
		// TODO Auto-generated method stub

		Subject subject = SecurityUtils.getSubject();
		// 使用shiro认证
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginRequest.getUserName(),
				loginRequest.getPassword());
		subject.login(usernamePasswordToken);
		addUserLoginLog(request, loginRequest.getUserName(), loginRequest.getClient());

	}

	/**
	 * 保存登录日志
	 * @param userName
	 * @throws Exception
	 */
	public void addUserLoginLog(HttpServletRequest request, String userName, String client) throws Exception {
		// 更新最近登录ip和时间
		TfUUserExample example = new TfUUserExample();
		example.or().andUserNameEqualTo(userName);
		TfUUser user = new TfUUser();
		user.setUpdateTime(new Date());
		user.setUpdateStaffId(user.getUserName());
		user.setLastLoginTime(new Date());
		user.setLastLoginIp(request.getRemoteHost());
		tfUUserMapper.updateByExampleSelective(user, example);
		// 插入日志表
		TfLoginLog log = new TfLoginLog();
		log.setLoginIp(request.getRemoteHost());
		log.setCreateStaffId(userName);
		log.setLoginTime(new Date());
		log.setUserId(subject.getPrincipal().getUserId());
		log.setCreateTime(new Date());
		// 好像暂时用不到
		log.setLoginClient(client);
		tfLoginLogMapper.insert(log);
	}


	@Override
	public int insertList(List<TfUUser> recordList) {
		// TODO Auto-generated method stub
		int count = 0;
		for (TfUUser item : recordList) {
			try {
				count += tfUUserMapper.insert(item);
			} catch (Exception e) {
				// TODO: handle exception
				logger.error("insert Exception{}" + e.getMessage());
				throw new RuntimeException();
			}

		}

		return count;
	}

	@Override
	public List<TfUUser> getDeveloperUser() {
		TfUUserExample tfUUserExample = new TfUUserExample();
		TfUUserExample.Criteria criteria = tfUUserExample.createCriteria();
		criteria.andUserTypeEqualTo(UserTypeConstants.ADMIN).andUserStateEqualTo("01");
		TfUUserExample.Criteria criteria2 = tfUUserExample.createCriteria();
		criteria2.andUserTypeEqualTo(UserTypeConstants.DEVELOPER).andUserStateEqualTo("01");
		tfUUserExample.or(criteria2);
		List<TfUUser> developersList = this.selectByExample(tfUUserExample);
		return developersList;
	}

	@Override
	public TfUUser selectUserByUserName(String userName) {
		TfUUserExample TfUUserExample = new TfUUserExample();
		TfUUserExample.createCriteria().andUserNameEqualTo(userName);
		List<TfUUser> TfUUsers = tfUUserMapper.selectByExample(TfUUserExample);
		if (null != TfUUsers && TfUUsers.size() > 0) {
			return TfUUsers.get(0);
		}
		return null;
	}

	@Override
	public void checkLogin(LoginRequest request) throws Exception {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(request.getUserName())) {
			throw new Exception("帐号不能为空！");
		}
		if (StringUtils.isBlank(request.getPassword())) {
			throw new Exception("密码不能为空！");
		}
	}

	@Override
	public TfLoginLog getLastloginInfo(Integer userId) {
		// TODO Auto-generated method stub
		TfLoginLogExample example = new TfLoginLogExample();
		example.or().andUserIdEqualTo(userId);
		example.setOrderByClause("login_time desc");
		example.setOffset(1);
		example.setLimit(1);
		List<TfLoginLog> list = tfLoginLogMapper.selectByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}


	@Override
	public List<VUserRole> getUserRole(Integer userId) {
		// TODO Auto-generated method stub
		VUserRoleExample example = new VUserRoleExample();
		example.or().andUserIdEqualTo(userId).andRoleStateEqualTo("01");
		List<VUserRole> list = vUserRoleMapper.selectByExample(example);
		return list;
	}

	@Override
	public void saveWork(SaveWorkRequest request) throws Exception {
		// TODO Auto-generated method stub
		TfWorkRecord tfWorkRecord = new TfWorkRecord();
		tfWorkRecord.setDetail(request.getDescription());
		tfWorkRecord.setCreateTime(new Date());
		tfWorkRecord.setCreateStaffId(subject.getPrincipal().getUserName());
		tfWorkRecord.setUserId(subject.getPrincipal().getUserId());
		tfWorkRecord.setDate(request.getDate());
		tfWorkRecordMapper.insert(tfWorkRecord);
		if (StringUtils.isNotEmpty(request.getClose()) && request.getClose().equals("on")) {
			TfUserDailyRecord record = new TfUserDailyRecord();
			record.setCreateStaffId(subject.getPrincipal().getUserName());
			record.setCreateTime(new Date());
			record.setIsExercise(request.getExercise());
			record.setIsRead(request.getStudy());
			record.setIsSleepEarly(request.getSleep());
			record.setIsGetUpEarly(request.getGetUp());
			record.setRemark(request.getRemark());
			record.setDate(request.getDate());
			record.setWeight(request.getWeight());
			record.setUserId(subject.getPrincipal().getUserId());
			tfUserDailyRecordMapper.insert(record);
		}
	}

	@Override
	public List<TfUserDailyRecord> queryDailyLife(QueryDailyLifeRequest request) {
		// TODO Auto-generated method stub
		TfUserDailyRecordExample example = new TfUserDailyRecordExample();
		String date = "%";
		if (StringUtils.isNotEmpty(request.getYearType()) || StringUtils.isNotEmpty(request.getMonthType())) {
			if (StringUtils.isNotEmpty(request.getYearType())) {
				date += request.getYearType() + "%";
			}
			if (StringUtils.isNotEmpty(request.getMonthType())) {
				date += "-" + request.getMonthType() + "%";
			}
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId()).andDateLike(date);
		} else {
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId());
		}
		example.setOffset(request.getOffset());
		example.setLimit(request.getLimit());
		example.setOrderByClause("create_time desc");
		return tfUserDailyRecordMapper.selectByExample(example);
	}

	@Override
	public long queryDailyLifeCount(QueryDailyLifeRequest request) {
		// TODO Auto-generated method stub
		TfUserDailyRecordExample example = new TfUserDailyRecordExample();
		String date = "";
		if (StringUtils.isNotEmpty(request.getYearType()) || StringUtils.isNotEmpty(request.getMonthType())) {
			if (StringUtils.isNotEmpty(request.getYearType())) {
				date += request.getYearType();
			}
			if (StringUtils.isNotEmpty(request.getMonthType())) {
				date += "-" + request.getMonthType();
			}
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId()).andDateLike(date);
		} else {
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId());
		}
		return tfUserDailyRecordMapper.countByExample(example);
	}

	@Override
	public void saveUser(SaveUserRequest request) throws Exception {
		if (checkUserInput(request.getUserName())) {

			Integer userId = insertTfUUser(request);
			if (StringUtils.isNotEmpty(request.getClose()) && request.getClose().equals("on")) {
				insertTfUDetail(userId, request);
			}
		}
	}

	public Integer insertTfUUser(SaveUserRequest request) throws Exception {
		TfUUser tfUUser = new TfUUser();
		tfUUser.setCreateStaffId(subject.getPrincipal().getUserName());
		tfUUser.setCreateTime(new Date());
		tfUUser.setPassword(request.getPassword());
		tfUUser.setRealName(request.getRealName());
		tfUUser.seteMail(request.getEmail());
		tfUUser.setUserName(request.getUserName());
		tfUUser.setUserType(request.getUserType());
		tfUUser.setUserState("01");
		tfUUser.setMobile(request.getMobile());
		tfUUser.setIdNo(request.getIdNo());
		tfUUserMapper.insert(tfUUser);
		return tfUUser.getUserId();
	}

	/**
	  * 校验用户信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public boolean checkUserInput(String userName) throws Exception {
		TfUUserExample example = new TfUUserExample();
		example.or().andUserNameEqualTo(userName);
		List<TfUUser> list = tfUUserMapper.selectByExample(example);
		if (list.size() > 0) {
			throw new Exception("账号已存在");
		}
		return true;
	}

	public void insertTfUDetail(Integer userId, SaveUserRequest request) throws Exception {
		TfUDetail tfUDetail = new TfUDetail();
		tfUDetail.setCid(request.getCity());
		tfUDetail.setPid(request.getProvince());
		tfUDetail.setSchool(request.getSchool());
		if (StringUtils.isNotEmpty(request.getIdNo())) {
			String birthDay = getBirthDayByIdNo(request.getIdNo());
			tfUDetail.setLunarCalendarBirthday(birthDay);
			tfUDetail.setEnglishBirthday(getBirthDayYingLByYangL(request.getIdNo()));
		}
		tfUDetail.setSchool(request.getSchool());
		tfUDetail.setSex(request.getSex());
		tfUDetail.setWork(request.getWork());
		tfUDetail.setSingle(request.getSingleType());
		tfUDetail.setUserId(userId);
		tfUDetail.setRemark(request.getRemark());
		tfUDetail.setAddress(request.getAddress());
		tfUDetail.setCreateTime(new Date());
		tfUDetail.setCreateStaffId(subject.getPrincipal().getUserName());
		tfUDetailMapper.insert(tfUDetail);
	}

	@Override
	public void saveTarget(SaveTargetRequest request) throws Exception {
		// TODO Auto-generated method stub
		Integer targetId = addTdTarget(request);
		addTmUUserTarget(targetId);
	}

	public int addTdTarget(SaveTargetRequest request) {
		// TODO Auto-generated method stub
		TdTarget tdTarget = new TdTarget();
		tdTarget.setTargetState("00");
		tdTarget.setTargetType(request.getTargetType());
		tdTarget.setContext(request.getTarget());
		tdTarget.setCreateStaffId(subject.getPrincipal().getUserName());
		tdTarget.setCreateTime(new Date());
		tdTargetMapper.insert(tdTarget);
		return tdTarget.getTargetId();
	}

	public void addTmUUserTarget(Integer targetId) {
		// TODO Auto-generated method stub
		TmUUserTarget tmUUserTarget = new TmUUserTarget();
		tmUUserTarget.setTargetId(targetId);
		tmUUserTarget.setIsDeleted("0");
		tmUUserTarget.setCreateStaffId(subject.getPrincipal().getUserName());
		tmUUserTarget.setCreateTime(new Date());
		tmUUserTarget.setUserId(subject.getPrincipal().getUserId());
		tmUUserTargetMapper.insert(tmUUserTarget);

	}

	@Override
	public void saveStory(SaveStoryRequest request) throws Exception {
		// TODO Auto-generated method stub
		Integer storyId = addTdStory(request);
		addTmUUserStory(storyId);
	}

	public int addTdStory(SaveStoryRequest request) {
		// TODO Auto-generated method stub
		TdStory tdStory = new TdStory();
		tdStory.setStoryType(request.getStoryType());
		tdStory.setContext(request.getStory());
		tdStory.setCreateStaffId(subject.getPrincipal().getUserName());
		tdStory.setCreateTime(new Date());
		tdStory.setDate(request.getDate());
		tdStoryMapper.insert(tdStory);
		return tdStory.getStoryId();
	}

	public void addTmUUserStory(Integer storyId) {
		// TODO Auto-generated method stub
		TmUUserStory tmUUserStory = new TmUUserStory();
		tmUUserStory.setStoryId(storyId);
		tmUUserStory.setIsDeleted(IsDeletedConstants.IN_USE);
		tmUUserStory.setCreateStaffId(subject.getPrincipal().getUserName());
		tmUUserStory.setCreateTime(new Date());
		tmUUserStory.setUserId(subject.getPrincipal().getUserId());
		tmUUserStoryMapper.insert(tmUUserStory);

	}

	@Override
	public long userTargetCountQuery(VUserTargetExample example) {
		// TODO Auto-generated method stub
		return vUserTargetMapper.countByExample(example);
	}

	@Override
	public List<VUserTarget> userTargetQuery(VUserTargetExample example) {
		// TODO Auto-generated method stub
		return vUserTargetMapper.selectByExampleWithBLOBs(example);
	}

	@Override
	public long userStoryCountQuery(VUserStoryExample example) {
		// TODO Auto-generated method stub
		return vUserStoryMapper.countByExample(example);
	}

	@Override
	public List<VUserStory> userStoryQuery(VUserStoryExample example) {
		// TODO Auto-generated method stub
		return vUserStoryMapper.selectByExampleWithBLOBs(example);
	}

	@Override
	public List<TfWorkRecord> queryDailyWork(QueryDailyWorkRequest request) {
		// TODO Auto-generated method stub
		TfWorkRecordExample example = new TfWorkRecordExample();
		String date = "%";
		if (StringUtils.isNotEmpty(request.getYearType()) || StringUtils.isNotEmpty(request.getMonthType())) {
			if (StringUtils.isNotEmpty(request.getYearType())) {
				date += request.getYearType() + "%";
			}
			if (StringUtils.isNotEmpty(request.getMonthType())) {
				date += "-" + request.getMonthType() + "-%";
			}
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId()).andDateLike(date);
		} else {
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId());
		}
		example.setOffset(request.getOffset());
		example.setLimit(request.getLimit());
		example.setOrderByClause("create_time desc");
		return tfWorkRecordMapper.selectByExample(example);
	}

	@Override
	public long queryDailyWorkCount(QueryDailyWorkRequest request) {
		// TODO Auto-generated method stub
		TfWorkRecordExample example = new TfWorkRecordExample();
		String date = "%";
		if (StringUtils.isNotEmpty(request.getYearType()) || StringUtils.isNotEmpty(request.getMonthType())) {
			if (StringUtils.isNotEmpty(request.getYearType())) {
				date += request.getYearType();
			}
			if (StringUtils.isNotEmpty(request.getMonthType())) {
				date += "-" + request.getMonthType() + "-%";
			}
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId()).andDateLike(date);
		} else {
			example.or().andUserIdEqualTo(subject.getPrincipal().getUserId());
		}
		return tfWorkRecordMapper.countByExample(example);
	}

	@Override
	public boolean checkWorkRequest(SaveWorkRequest request) throws Exception {
		// TODO Auto-generated method stub
		TfWorkRecordExample tfWorkRecordExample = new TfWorkRecordExample();
		tfWorkRecordExample.or().andUserIdEqualTo(subject.getPrincipal().getUserId()).andDateEqualTo(request.getDate());
		return tfWorkRecordMapper.countByExample(tfWorkRecordExample) < 1;
	}

	@Override
	public UpdateTargetResponse updateTarget(UpdateTargetRequest request) {
		UpdateTargetResponse response = new UpdateTargetResponse();
		// TODO Auto-generated method stub
		TdTarget tdTarget = new TdTarget();
		tdTarget = tdTargetMapper.selectByPrimaryKey(request.getTargetId());
		if (tdTarget != null) {
			tdTarget.setUpdateTime(new Date());
			tdTarget.setTargetState(request.getState());
			tdTarget.setContext(request.getContext());
			tdTarget.setUpdateStaffId(subject.getPrincipal().getUserName());
			int count = tdTargetMapper.updateByPrimaryKeyWithBLOBs(tdTarget);
			if (count > 0) {
				response.setCode(CodeConstants.SUCCESS);
				response.setMessage("更新成功");
			} else {
				response.setCode(CodeConstants.FAIL);
				response.setMessage("更新失败");
			}
		} else {
			response.setCode(CodeConstants.FAIL);
			response.setMessage("更新失败:未找到改目标");
		}
		return response;
	}

	@Override
	public TfUDetail selectByUserId(Integer userId) {
		// TODO Auto-generated method stub
		return tfUDetailMapper.selectByPrimaryKey(userId);
	}

	@Override
	public void updateUser(UpdateUserRequest request) throws Exception {
		if (request.getUserName().equals(subject.getPrincipal().getUserName())
				|| checkUserInput(request.getUserName())) {
			updateTfUUser(request);
			if (StringUtils.isNotEmpty(request.getClose()) && request.getClose().equals("on")) {
				if (checkTfUDetailExist(subject.getPrincipal().getUserId())) {
					updateTfUDetail(request);
				} else {
					insertUserDetail(subject.getPrincipal().getUserId(), request);
				}

			}
		}
	}

	public void insertUserDetail(Integer userId, UpdateUserRequest request) throws Exception {
		TfUDetail tfUDetail = new TfUDetail();
		tfUDetail.setCid(request.getCity());
		tfUDetail.setPid(request.getProvince());
		tfUDetail.setSchool(request.getSchool());
		if (StringUtils.isNotEmpty(request.getIdNo())) {
			String birthDay = getBirthDayByIdNo(request.getIdNo());
			tfUDetail.setLunarCalendarBirthday(birthDay);
			tfUDetail.setEnglishBirthday(getBirthDayYingLByYangL(request.getIdNo()));
		}
		tfUDetail.setSchool(request.getSchool());
		tfUDetail.setSex(request.getSex());
		tfUDetail.setWork(request.getWork());
		tfUDetail.setSingle(request.getSingleType());
		tfUDetail.setUserId(userId);
		tfUDetail.setCreateTime(new Date());
		tfUDetail.setCreateStaffId(subject.getPrincipal().getUserName());
		tfUDetail.setAddress(request.getAddress());
		tfUDetailMapper.insert(tfUDetail);
	}

	public boolean checkTfUDetailExist(Integer userId) throws Exception {
		return tfUDetailMapper.selectByPrimaryKey(userId) != null;
	}

	public void updateTfUDetail(UpdateUserRequest request) throws Exception {
		TfUDetail tfUDetail = new TfUDetail();
		tfUDetail.setCid(request.getCity());
		tfUDetail.setPid(request.getProvince());
		tfUDetail.setSchool(request.getSchool());
		if (StringUtils.isNotEmpty(request.getIdNo())) {
			String birthDay = getBirthDayByIdNo(request.getIdNo());
			tfUDetail.setLunarCalendarBirthday(birthDay);
			tfUDetail.setEnglishBirthday(getBirthDayYingLByYangL(request.getIdNo()));
		}
		tfUDetail.setAddress(request.getAddress());
		tfUDetail.setSchool(request.getSchool());
		tfUDetail.setSex(request.getSex());
		tfUDetail.setWork(request.getWork());
		tfUDetail.setSingle(request.getSingleType());
		tfUDetail.setUserId(subject.getPrincipal().getUserId());
		tfUDetail.setUpdateTime(new Date());
		tfUDetail.setUpdateStaffId(subject.getPrincipal().getUserName());
		tfUDetailMapper.updateByPrimaryKeySelective(tfUDetail);
	}

	public void updateTfUUser(UpdateUserRequest request) throws Exception {
		TfUUser tfUUser = new TfUUser();
		tfUUser.setUpdateStaffId(subject.getPrincipal().getUserName());
		tfUUser.setUpdateTime(new Date());
		tfUUser.setRealName(request.getRealName());
		tfUUser.seteMail(request.getEmail());
		tfUUser.setUserName(request.getUserName());
		tfUUser.setIdNo(request.getIdNo());
		tfUUser.setMobile(request.getMobile());
		tfUUser.setUserId(subject.getPrincipal().getUserId());
		tfUUserMapper.updateByPrimaryKeySelective(tfUUser);
		subject.getPrincipal().seteMail(request.getEmail());
		subject.getPrincipal().setIdNo(request.getIdNo());
		subject.getPrincipal().setMobile(request.getMobile());
		subject.getPrincipal().setRealName(request.getRealName());
		subject.getPrincipal().setUserName(request.getUserName());
	}

	@Override
	public void updateUserPassword(UpdatePasswordRequest request) throws Exception {
		// TODO Auto-generated method stub
		if (checkPassword(request)) {
			TfUUser tfUUser = new TfUUser();
			tfUUser.setPassword(request.getNewPassword());
			tfUUser.setUserId(subject.getPrincipal().getUserId());
			tfUUserMapper.updateByPrimaryKeySelective(tfUUser);
		}
	}

	public boolean checkPassword(UpdatePasswordRequest request) throws Exception {
		if (!request.getPassword().equals(subject.getPrincipal().getPassword())) {
			throw new Exception("密码错误");
		}
		if (request.getNewPassword().equals(subject.getPrincipal().getPassword())) {
			throw new Exception("新密码与老密码不能一致");
		}
		if (!request.getNewPassword().equals(request.getNewPasswordConfirm())) {
			throw new Exception("新密码与密码确认不一致");
		}
		return true;
	}

	@Override
	public String selectBirthDayRemindUser() throws Exception {
		// TODO Auto-generated method stub
		StringBuffer stringBuffer = new StringBuffer();
		TfUUserExample example = new TfUUserExample();
		example.or().andUserIdNotEqualTo(subject.getPrincipal().getUserId());
		List<TfUUser> tfUUsers = tfUUserMapper.selectByExample(example);
		for (TfUUser user : tfUUsers) {
			if (StringUtils.isNotEmpty(user.getIdNo()) && user.getIdNo().length() == 18) {
				String d = user.getIdNo().substring(6, 14);
				Calendar today = Calendar.getInstance();
				Calendar today2 = Calendar.getInstance();
				today.setTime(dateFormat.parse(d));
				LunarUtil lunar = new LunarUtil(today);
				Lunar l = new Lunar();
				l.isleap = false;
				l.lunarDay = lunar.getDay();
				l.lunarMonth = lunar.getMonth();
				l.lunarYear = today2.get(Calendar.YEAR);
				Solar solar = LunarSolarConverter.LunarToSolar(l);
				long date = printDifference(new Date(), chineseDateFormat.parse(solar.toString()));
				if (date > 0 && date < 10) {
					stringBuffer.append(user.getRealName()).append("的阴历生日是").append(lunar.toString()).append(";<br/>")
							.append("本年度的阴历生日对应的阳历是").append(solar.toString()).append(";<br/>距离生日还有").append(date)
							.append("天;<br/>");
				}

			}
		}
		return stringBuffer.toString();
	}

	public static long printDifference(Date startDate, Date endDate) {

		// milliseconds
		long different = endDate.getTime() - startDate.getTime(); // 此时精确到微妙
		different /= 1000 * 60 * 60 * 24; // 转成秒数
		different += 1;
		return different >= 0 ? different : 0;

	}

	@Override
	public void saveSummary(SaveSummaryRequest request) throws Exception {
		// TODO Auto-generated method stub
		TfUserDailySummary tfUserDailySummary = new TfUserDailySummary();
		tfUserDailySummary.setContent(request.getContent());
		tfUserDailySummary.setDate(request.getDate());
		tfUserDailySummary.setCreateStaffId(subject.getPrincipal().getUserName());
		tfUserDailySummary.setIsDeleted(IsDeletedConstants.IN_USE);
		tfUserDailySummary.setCreateTime(new Date());
		tfUserDailySummary.setDateType(request.getDateType());
		tfUserDailySummary.setSummaryType(request.getSummaryType());
		tfUserDailySummary.setUserId(subject.getPrincipal().getUserId());
		tfUserDailySummaryMapper.insertSelective(tfUserDailySummary);
	}

	@Override
	public long userSummaryCountQuery(VUserDailySummaryExample example) {
		// TODO Auto-generated method stub
		return vUserDailySummaryMapper.countByExample(example);
	}

	@Override
	public List<VUserDailySummary> userSummaryQuery(VUserDailySummaryExample example) {
		// TODO Auto-generated method stub
		return vUserDailySummaryMapper.selectByExampleWithBLOBs(example);
	}

	@Override
	public void deleteTarget(DeleteTargetRequest request) {
		// TODO Auto-generated method stub
		TmUUserTargetExample example = new TmUUserTargetExample();
		example.or().andTargetIdEqualTo(request.getTargetId());
		TmUUserTarget tmUUserTarget = new TmUUserTarget();
		tmUUserTarget.setIsDeleted(IsDeletedConstants.DELETED);
		tmUUserTarget.setUpdateStaffId(subject.getPrincipal().getUserName());
		tmUUserTarget.setUpdateTime(new Date());
		tmUUserTargetMapper.updateByExampleSelective(tmUUserTarget, example);

	}

	@Override
	public void deleteSummary(DeleteSummaryRequest request) {
		// TODO Auto-generated method stub
		TfUserDailySummary tfUserDailySummary =new TfUserDailySummary();
		tfUserDailySummary.setId(request.getId());
		tfUserDailySummary.setIsDeleted(IsDeletedConstants.DELETED);
		tfUserDailySummary.setUpdateTime(new Date());
		tfUserDailySummary.setUpdateStaffId(subject.getPrincipal().getUserName());
		tfUserDailySummaryMapper.updateByPrimaryKeySelective(tfUserDailySummary);
	}

	@Override
	public long userListCountQuery(VUserExample example) {
		// TODO Auto-generated method stub
		return VUserMapper.countByExample(example);
	}

	@Override
	public List<VUser> userListQuery(VUserExample example) {
		// TODO Auto-generated method stub
		return VUserMapper.selectByExample(example);
	}

	@Override
	public List<TdRole> roleListQuery(TdRoleExample example) {
		// TODO Auto-generated method stub
		return tdRoleMapper.selectByExample(example);
	}

	@Override
	public List<VUserRole> userRoleListQuery(VUserRoleExample example) {
		// TODO Auto-generated method stub
		return vUserRoleMapper.selectByExample(example);
	}

	@Override
	public List<VRolePermission> rolePermissionListQuery(VRolePermissionExample example) {
		// TODO Auto-generated method stub
		return vRolePermissionMapper.selectByExample(example);
	}

	@Override
	public void updateUserRole(UpdateUserRoleRequest request) {
		// TODO Auto-generated method stub
		// 分3种 已有角色不动，已有角色删除 新增角色。
		VUserRoleExample example =new VUserRoleExample();
		example.or().andUserIdEqualTo(request.getUserId());
		List<VUserRole> list = vUserRoleMapper.selectByExample(example);
		Set<Integer> set1 = new HashSet<Integer>(list.size());
		for (VUserRole item : list) {
			set1.add(item.getRoleId());
		}
		String roleList = request.getRoleIdList();
		String[] roleList2 = roleList.split(",");
		for (String item : roleList2) {
			if (set1.contains(Integer.valueOf(item))) {
				// 已有角色不动
				set1.remove(Integer.valueOf(item));
			} else {
				// 新增的
				TmUUserRole tmUUserRole = new TmUUserRole();
				tmUUserRole.setUserId(request.getUserId());
				tmUUserRole.setRoleId(Integer.valueOf(item));
				tmUUserRole.setIsDeleted(IsDeletedConstants.IN_USE);
				tmUUserRole.setCreateTime(new Date());
				tmUUserRole.setCreateStaffId(subject.getPrincipal().getUserName());
				tmUUserRoleMapper.insertSelective(tmUUserRole);
			}
		}
		Iterator<Integer> it = set1.iterator();
		while (it.hasNext()) {
			Integer str = it.next();
			// 已有角色删除
			TmUUserRoleExample tmUUserRoleExample = new TmUUserRoleExample();
			tmUUserRoleExample.or().andUserIdEqualTo(request.getUserId()).andRoleIdEqualTo(str)
					.andIsDeletedEqualTo(IsDeletedConstants.IN_USE);
			TmUUserRole tmUUserRole = new TmUUserRole();
			tmUUserRole.setIsDeleted(IsDeletedConstants.DELETED);
			tmUUserRoleMapper.updateByExampleSelective(tmUUserRole, tmUUserRoleExample);
		}
	}

	@Override
	public long roleListCountQuery(TdRoleExample example) {
		// TODO Auto-generated method stub
		return tdRoleMapper.countByExample(example);
	}

	@Override
	public List<TdPermission> permissionListQuery(TdPermissionExample example) {
		// TODO Auto-generated method stub
		return tdPermissionMapper.selectByExample(example);
	}

	@Override
	public void updateRolePermission(UpdateRolePermissionRequest request) {
		// TODO Auto-generated method stub
		// 分3种 已有角色不动，已有角色删除 新增角色。
		VRolePermissionExample example = new VRolePermissionExample();
		example.or().andRoleIdEqualTo(request.getRoleId());
		List<VRolePermission> list = vRolePermissionMapper.selectByExample(example);
		Set<Integer> set1 = new HashSet<Integer>(list.size());
		for (VRolePermission item : list) {
			set1.add(item.getPermissionId());
		}
		String permissionList = request.getPermissionList();
		String[] permissionList2 = permissionList.split(",");
		for (String item : permissionList2) {
			if (set1.contains(Integer.valueOf(item))) {
				// 已有角色不动
				set1.remove(Integer.valueOf(item));
			} else {
				// 新增的
				TmRRolePermission tmRRolePermission = new TmRRolePermission();
				tmRRolePermission.setRoleId(request.getRoleId());
				tmRRolePermission.setPermissionId(Integer.valueOf(item));
				tmRRolePermission.setIsDeleted(IsDeletedConstants.IN_USE);
				tmRRolePermission.setCreateTime(new Date());
				tmRRolePermission.setCreateStaffId(subject.getPrincipal().getUserName());
				tmRRolePermissionMapper.insertSelective(tmRRolePermission);
			}
		}
		Iterator<Integer> it = set1.iterator();
		while (it.hasNext()) {
			Integer str = it.next();
			// 已有角色删除
			TmRRolePermissionExample tmRRolePermissionExample = new TmRRolePermissionExample();
			tmRRolePermissionExample.or().andRoleIdEqualTo(request.getRoleId()).andPermissionIdEqualTo(str)
					.andIsDeletedEqualTo(IsDeletedConstants.IN_USE);
			TmRRolePermission tmRRolePermission = new TmRRolePermission();
			tmRRolePermission.setIsDeleted(IsDeletedConstants.DELETED);
			tmRRolePermissionMapper.updateByExampleSelective(tmRRolePermission, tmRRolePermissionExample);
		}
	}

	@Override
	public long storyBudgetListCountQuery(VUserBudgetExample example) {
		// TODO Auto-generated method stub
		return vUserBudgetMapper.countByExample(example);
	}

	@Override
	public List<VUserBudget> storyBudgetListQuery(VUserBudgetExample example) {
		// TODO Auto-generated method stub
		return vUserBudgetMapper.selectByExample(example);
	}

	@Override
	public void addStoryBudget(SaveBudgetRequest request) throws Exception {
		// TODO Auto-generated method stub
		Integer budgetId = addTfBudget(request);
		addTmSStoryBudget(request.getStoryId(), budgetId);

	}

	public Integer addTfBudget(SaveBudgetRequest request) {
		TfBudget record = new TfBudget();
		record.setChannelId(request.getChannelId());
		record.setGoods(request.getGoods());
		record.setMoney(request.getMoney());
		record.setNumber(request.getNumber());
		record.setUnitPrice(request.getUnitPrice());
		record.setRemark(request.getRemark());
		record.setCreateTime(new Date());
		record.setCreateStaffId(subject.getPrincipal().getUserName());
		tfBudgetMapper.insert(record);
		return record.getBudgetId();
	}
	public void addTmSStoryBudget(Integer storyId, Integer budgetId) {
		TmSStoryBudget record = new TmSStoryBudget();
		record.setBudgetId(budgetId);
		record.setStoryId(storyId);
		record.setIsDeleted(IsDeletedConstants.IN_USE);
		record.setCreateTime(new Date());
		record.setCreateStaffId(subject.getPrincipal().getUserName());
		tmSStoryBudgetMapper.insert(record);
	}

	@Override
	public void updateStoryBudget(SaveBudgetRequest request) throws Exception {
		// TODO Auto-generated method stub
		TfBudget record = new TfBudget();
		record.setBudgetId(request.getBudgetId());
		record.setChannelId(request.getChannelId());
		record.setGoods(request.getGoods());
		record.setMoney(request.getMoney());
		record.setNumber(request.getNumber());
		record.setUnitPrice(request.getUnitPrice());
		record.setRemark(request.getRemark());
		record.setUpdateTime(new Date());
		record.setUpdateStaffId(subject.getPrincipal().getUserName());
		tfBudgetMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public void deleteStoryBudget(DeleteStoryBudgetRequest request) throws Exception {
		// TODO Auto-generated method stub
		TmSStoryBudgetExample example = new TmSStoryBudgetExample();
		example.or().andBudgetIdEqualTo(request.getBudgetId()).andStoryIdEqualTo(request.getStoryId());
		TmSStoryBudget record = new TmSStoryBudget();
		record.setUpdateStaffId(subject.getPrincipal().getUserName());
		record.setUpdateTime(new Date());
		record.setIsDeleted(IsDeletedConstants.DELETED);
		tmSStoryBudgetMapper.updateByExampleSelective(record, example);
	}

	@Override
	public void saveRole(SaveRoleRequest request) throws Exception {
		// TODO Auto-generated method stub
		TdRole tdRole = new TdRole();
		tdRole.setCreateStaffId(subject.getPrincipal().getUserName());
		tdRole.setCreateTime(new Date());
		tdRole.setDescription(request.getDescription());
		tdRole.setRoleName(request.getRoleName());
		tdRole.setRoleState("01");
		tdRoleMapper.insertSelective(tdRole);
	}

}